import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.Config;
import com.kylin.module.ad.business.ADBlogic;
import com.kylin.module.ad.orm.AD;

public class FileOutServlet extends HttpServlet {
	protected static Logger log = Logger.getLogger(FileOutServlet.class);

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.debug(""+request.getParameter("fileType"));
		if("openADLink".equals(request.getParameter("CMD")) ){
			ADBlogic blogic = new ADBlogic();
			String link="";
			AD ad;
			try {
				ad = (AD)blogic.getADById(new Long(request.getParameter("id")));
				link = ad.getLink();
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("link="+link);
			PrintWriter out = response.getWriter();
			out.print("<a href='"+link+"'>"+link+"</a>");
			response.sendRedirect(link);
			return;
		}
		if(request.getParameter("imgType") != null){
			File image = new File(Config.uploadFileDir + request.getParameter("imgType") + File.separator + request.getParameter("imgurl"));
			if(! image.exists())
				image = new File(getServletContext().getRealPath("/images/")+ File.separator + "null.jpg");
			outImg( response, image);
		}else if(request.getParameter("fileType") != null){
			File mediaFile = new File(Config.uploadFileDir + request.getParameter("fileType") + File.separator + request.getParameter("fileUrl"));
			log.debug("mediaFile==="+mediaFile.getPath());
			if(! mediaFile.exists())
				mediaFile = new File(getServletContext().getRealPath("/images/")+ File.separator + "null.jpg");
			outMedia( response, mediaFile);
		}
	}

	/**
	 * 输出图片文件流
	 * @param response
	 * @param image
	 * @throws IOException
	 */
	private void outImg(HttpServletResponse response,File image) throws IOException{
//if(image != null)
//("outImage="+image.getPath());
		String ext = "";
		int idx = image.getName().lastIndexOf(".");
		if (idx > 0 && idx < image.getName().length()) {
			ext = image.getName().substring(idx + 1, image.getName().length());
		}
		String outputType = "image/" + ext;
	    response.setHeader("Content-disposition", "filename=\"" + image.getName() + "\";");
	    response.setContentType(outputType);
		response.setContentLength((int)image.length());	
		OutputStream out = response.getOutputStream();
		outFileData( out, image);
	}
	
	/**
	 * 输出多媒体文件流
	 * @param response
	 * @param media
	 * @throws IOException
	 */
	private void outMedia(HttpServletResponse response,File media) throws IOException{
		log.debug("-----outMedia:"+media.getPath());
		String contype="application/octet-stream";
		String ext = "";
		int idx = media.getName().lastIndexOf(".");
		if (idx > 0 && idx < media.getName().length()) {
			ext = media.getName().substring(idx + 1, media.getName().length());
		}
		if("swf".equals(ext)){
			contype = "application/x-shockwave-flash";
		} 
		response.setHeader("Content-disposition", "filename=\"" + media.getName() + "\";");
	    response.setContentType(contype);
		response.setContentLength((int)media.length());	
		OutputStream out = response.getOutputStream();
		outFileData( out, media);	
		out.close();
	}
	
	/**
	 * 输出文件数据流
	 * @param out
	 * @param file
	 * @throws IOException
	 */
	private void outFileData(OutputStream out,File file) throws IOException  {
		log.debug("outFileData:"+file.getPath());
		InputStream in = new FileInputStream(file);
		byte[]buffer = new byte[2048];
		int pos = in.read(buffer);
		while(pos != -1){
			out.write(buffer,0,pos);
			pos = in.read(buffer);
		}
		out.flush();
		in.close();
	}
}
